package com.bridgeintelligent.tag.webserver.security;

import com.bridgeintelligent.tag.utils.PropertityUtil;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取项目的IP和端口
 *
 * @Owner:
 * @Time: 2019/2/22-16:21
 */


@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
    public int getServerPort() {
        return serverPort;
    }

    private int serverPort;

    private String reqIp = PropertityUtil.srv("constant.properties", "server.req.ip");


    public String getUrl() {
        // InetAddress address = null;
        // try {
        //     address = InetAddress.getLocalHost();
        // } catch (UnknownHostException e) {
        //     e.printStackTrace();
        // }
//        return "http://"+address.getHostAddress()+":"+this.serverPort;
        return "http://" + reqIp + ":" + this.serverPort;
    }

    public String getHost() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
            return address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "";

    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        serverPort = event.getWebServer().getPort();
    }
}

